import datetime, time
from decimal import Decimal
from profiler.profiler import *
from notifier.notifier import *
from cache.cache import *

p1 = HecateProfiler(1)
p2 = HecateProfiler(2)
n = HecateNotifier()
cache = Cache()

#open profile1
time_format = "%Y/%m/%d/%H:%M:%S"
def a1_cb(objs):
	print 'a1 callback'
	if not objs:
		return
	for obj in objs:
		cache.Insert(obj)

def a2_cb(tags):
	print 'a2 callback'
	if not tags:
		return
	for tag in tags:
		cache.Insert(tag)

a1_le = HecateLocationEvent(1, 1, a1_cb, ['search', 'news'])
a1_te = HecateTimeEvent(1, 2, a1_cb, ['search', 'news'], time_interval=900)

a2_le = HecateLocationEvent(2, 3, a2_cb, ['nyse', 'nasdaq'], give_objs=False)
a2_te = HecateTimeEvent(2, 4, a2_cb, ['nyse', 'nasdaq'], time_interval=900, give_objs=False)

n.RegisterEvent(a1_le)
n.RegisterEvent(a1_te)
n.RegisterEvent(a2_le)
n.RegisterEvent(a2_te)

with open('profile1') as f:
	line = ''
	while line != '*experiment*\n':
		dt = f.readline()[:-1]
		#import pdb; pdb.set_trace()
		ts = datetime.fromtimestamp(time.mktime(time.strptime(dt, time_format)))
		lat = Decimal(f.readline())
		long = Decimal(f.readline())
		app = int(f.readline())
		obj = f.readline()
		line = f.readline()
		if app == 1:
			tags = []
			if obj == "google.com\n":
				tags.extend(['search'])
			elif obj == "yahoo.com\n":
				tags.extend(['search', 'news'])
			p1.TrackUsage(obj, ts, long, lat, tags)
		elif app == 2:
			tags = []
			if obj.startswith('nyse'):
				tags.extend(['nyse'])
			elif obj.startswith('nasdaq'):
				tags.extend(['nasdaq'])
			p2.TrackUsage(obj, ts, long, lat, tags)

	while line != 'end\n':
		dt = f.readline()[:-1]
		ts = datetime.fromtimestamp(time.mktime(time.strptime(dt, time_format)))
		lat = Decimal(f.readline())
		long = Decimal(f.readline())
		app = int(f.readline())
		obj = f.readline()
		line = f.readline()
		if app == 1:
			tags = []
			if obj == "google.com\n":
				tags.extend(['search'])
			elif obj == "yahoo.com\n":
				tags.extend(['search', 'news'])
			print "Checking App Events: " +	str(n.CheckAppEvents(1, Location(lat, long), ts))
			#check if obj/tag is in cache
			if cache.Query(cache.IndexItem(obj)):
				print "cache hit"
			else:
				print "cache miss"

			p1.TrackUsage(obj, ts, long, lat, tags)
		elif app == 2:
			tags = []
			if obj.startswith('nyse'):
				tags.extend(['nyse'])
			elif obj.startswith('nasdaq'):
				tags.extend(['nasdaq'])
			print "Checking App Events: " +	str(n.CheckAppEvents(2, Location(lat, long), ts))
			if cache.Query(cache.IndexItem(tags[0])):
				print "cache hit"
			else:
				print "cache miss"

			p2.TrackUsage(obj, ts, long, lat, tags)



